package com.osfans.trime;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * json工具类
 *
 * @date 2021-03-23
 */
public class JsonUtil {
    public static ArrayList<String> load(File path) {
        ArrayList<String> list = new ArrayList<>();
        if (!path.exists()) {
            return new ArrayList<>();
        }
        try (InputStream stream = new FileInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));) {
            StringBuilder stringBuilder = new StringBuilder();
            String input;
            while ((input = reader.readLine()) != null) {
                stringBuilder.append(input);
            }
            JSONArray letters = new JSONArray(stringBuilder.toString());
            int len = letters.length();
            for (int i = 0; i < len; i++) {
                list.add(letters.getString(i));
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
        return list;
    }


    public static void save(File path, List<String> map) {
        JSONArray json = new JSONArray(map);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8));) {
            writer.write(json.toString(4));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
